package ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.zzhoujay.richtext.RichText;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.AddImagePickerAdapter;
import application.App;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.NoteCategoryBean;
import bean.NoteDetailBean;
import jp.wasabeef.richeditor.RichEditor;
import student.andlei.com.student.R;
import utils.GsonUtils;
import utils.QiniuUploadUtils;
import utils.SPUtils;
import utils.StringUtils;

public class AddNewNoteActivity extends BaseNetActivity{
    private NiceSpinner spinner;
    private EditText ed_title;
    //private RichEditor retNoteContent;
    private RichEditor et_new_content;
    private List<String> spannerlist =  new ArrayList<>();
    private List<NoteCategoryBean> list = new ArrayList<>();
    private AddImagePickerAdapter adapter;
    private ImageView img_photo,img_camera,img_update;
    private LinearLayout llOverKeyBoard;
    private int category_id;
    private int note_id;
    private boolean isHandwritingBoardOpen;
    private String typename;
    //private Subscription subsInsert;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseBack(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        setBaseRightText("提交    ", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(note_id==0){
                    showLoadDialog();
                    Map<String,String> map = new HashMap<>();
                    map.put("category_id",category_id+"");
                    map.put("title",ed_title.getText().toString());
                    map.put("content",et_new_content.getHtml());
                    post("note/addNote",map,BaseBean.class,false);
                }else {
                    Map<String,String> map = new HashMap<>();
                    map.put("note_id",note_id+"");
                    map.put("category_id",category_id+"");
                    map.put("title",ed_title.getText().toString());
                   // et_new_content.setText(Html.fromHtml(et_new_content.getRichText()));
                    map.put("content",et_new_content.getHtml());
                    Log.i("et_new_content---->",et_new_content.getHtml()+"");
                    post("note/editNote",map,BaseBean.class,true);
                }

            }
        });

    }

    @Override
    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        if(baseBean.code == 200){
                if(action.equals("note/categoryList")){
                    list = GsonUtils.getInstance(context).parseNoHeaderJArray(baseBean, NoteCategoryBean.class);
                    for (NoteCategoryBean bean : list) {
                        spannerlist.add(bean.category_name);
                    }
                    if(list.size()>=1){
                        category_id = list.get(0).category_id;
                        spinner.attachDataSource(spannerlist);
                    }
                    for (int i =0 ;i<list.size(); i++) {
                        if(StringUtils.isNull(typename)){return;}
                        if(typename.equals(list.get(i).category_name)){
                            category_id = list.get(i).category_id;
                            spinner.setSelectedIndex(i);
                        }
                    }
                }else if(action.equals("note/addNote")){
                    toast("提交笔记成功");
                    setResult(4,new Intent().putExtra("category_id",category_id));
                    finish();
                }else if(action.equals("note/noteDetail")){
                    NoteDetailBean detailBean = (NoteDetailBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), NoteDetailBean.class);
                    ed_title.setText(detailBean.title);
                    category_id = detailBean.category_id;
                    loadData();
                    //在第一次调用RichText之前先调用RichText.initCacheDir()方法设置缓存目录，不设置会报错
                    Log.i("et_new_content---->s-",detailBean.content+"");
                    et_new_content.setHtml(detailBean.content);
                }else if(action.equals("note/editNote")){
                    toast("修改笔记成功");
                    finish();
                }
        }else {
            toast(baseBean.msg);
        }
    }
    private void initRichEditor() {
//        retNoteContent.setEditorHeight(DensityUtil.dip2px(EditNoteActivity.this,287));
        et_new_content.setEditorFontSize(20);
        et_new_content.setPlaceholder("请输入笔记内容");
        et_new_content.setEditorFontColor(getResources().getColor(R.color.font_black));
        et_new_content.setPadding(33, 26, 33, 26);
        et_new_content.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {
//                content=text;
//                Logger.i("Logger","content"+text);
            }
        });
    }
    private void initViewOverKeyBoard() {
        et_new_content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            //当键盘弹出隐藏的时候会 调用此方法。
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //获取当前界面可视部分
                AddNewNoteActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = AddNewNoteActivity.this.getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;
                //判断是否有虚拟按键
                Resources resources = getResources();
                int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
                if (resourceId > 0) {
                    int navigationBarHeight = resources.getDimensionPixelSize(resourceId);
                    heightDifference = heightDifference - navigationBarHeight;
                }
                Log.d("Keyboard Size", "Size: " + heightDifference);
               showViewOverKeyBoard(heightDifference);
            }

        });
    }
    private void showViewOverKeyBoard(int heightDifference) {

        if (isHandwritingBoardOpen) {
            llOverKeyBoard.setVisibility(View.VISIBLE);
        } else {
            if (et_new_content.isFocusable()) {
                if (heightDifference > 0) {//显示
                    //代码动态添加
                    llOverKeyBoard.setVisibility(View.VISIBLE);
                } else {//隐藏
                    if (llOverKeyBoard != null) {
                        llOverKeyBoard.setVisibility(View.GONE);
                    }
                }
            }
        }
    }
    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_addnote;
    }

    @Override
    protected void findViews() {
        RichText.initCacheDir(context);
        spinner = getView(R.id.spinner_type);
        ed_title = getView(R.id.ed_note_title);
        et_new_content = getView(R.id.ed_content);
//        et_new_content.setSaveEnabled(false);
//        et_new_content.setEnabled(false);
        llOverKeyBoard = getView(R.id.ll_overkeyboard_addnote);
        img_photo = getView(R.id.iv_picture_overkeyloard_addnote);
        img_camera= getView(R.id.iv_camera_overkeyloard_addnote);
        img_update = getView(R.id.iv_drawingboard_overkeyloard_addnote);
    }

    @Override
    protected void formatViews() {
        initRichEditor();
        img_photo.setOnClickListener(this);
        img_camera.setOnClickListener(this);
        img_update.setOnClickListener(this);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                for (NoteCategoryBean bean : list){
                    if(tv.getText().toString().equals(bean.category_name)){
                        category_id = list.get(position).category_id;
                    }
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        initViewOverKeyBoard();
    }
    private List<LocalMedia> selectList = new ArrayList<>();
    private void openPhoto() {
        PictureSelector.create(AddNewNoteActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(false)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }
    private void openCamera() {
        PictureSelector.create(AddNewNoteActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .selectionMedia(selectList)
                .forResult(PictureConfig.REQUEST_CAMERA);
    }
    @Override
    protected void formatData() {

    }
    private void loadData(){
        //获取分类列表
        Map<String, String> map = new HashMap<>();
        post("note/categoryList", map, NoteCategoryBean.class, false);
    }
    @Override
    protected void getBundle(Bundle bundle) {
            if(bundle!=null){
                if(bundle.getInt("note_id",0)!=0){
                    note_id = bundle.getInt("note_id",0);
                    setTitle("修改笔记");
                    Map<String, String> map = new HashMap<>();
                    map.put("note_id", "" + note_id);
                    post("note/noteDetail", map, BaseBean.class, false);
                }else {
                    setTitle("添加笔记");
                    loadData();
                }
                if(!StringUtils.isNull(bundle.getString("typename"))){
                    typename = bundle.getString("typename");
                }
            }else {
                setTitle("添加笔记");
                loadData();
            }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //选择图片
            case R.id.iv_picture_overkeyloard_addnote:
                openPhoto();
                break;
            //拍照
            case R.id.iv_camera_overkeyloard_addnote:
                openCamera();
                break;
            //添加手写板图
            case R.id.iv_drawingboard_overkeyloard_addnote:
                jumpTo(AddWacomActivity.class,0);
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = selectList.get(0);
                    String compressPath = localMedia.getCompressPath();

                    String qiniutoken = SPUtils.getInstance(App.getInstance()).getString("uptoken");
                    String key = System.currentTimeMillis() + "note.png";
                    QiniuUploadUtils.getInstance().uploadFile(compressPath, new QiniuUploadUtils.UploadListener() {
                        @Override
                        public void onUploadSuccess(String key) {
                            String yuming = SPUtils.getInstance(AddNewNoteActivity.this).getString("domain");
                            final String image = yuming+key;
                            et_new_content.insertImage(image, "\" style=\"max-width:100%");
                            selectList.clear();
                        }
                        @Override
                        public void onUploadFail(Error error) {

                        }
                    },qiniutoken);
                    break;
            }
        }
       else if(requestCode == 0){
            if(data!=null){
                QiniuUploadUtils.getInstance().uploadFile(data.getStringExtra("filename"), new QiniuUploadUtils.UploadListener() {
                    @Override
                    public void onUploadSuccess(String key) {
                        hideLoadDialog();
                        String yuming = SPUtils.getInstance(AddNewNoteActivity.this).getString("domain");
                        final String image = yuming+key;
                        et_new_content.insertImage(image, "\" style=\"max-width:100%");
                    }
                    @Override
                    public void onUploadFail(Error error) {
                        hideLoadDialog();
                        Looper.prepare();
                        toast("插入图片失败");
                        Looper.loop();
                    }
                },SPUtils.getInstance(AddNewNoteActivity.this).getString("uptoken"));
            }

        }
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
       hideLoadDialog();
    }
}
